import { tabbarPages } from "@/constants/pageMap"
import Taro from "@tarojs/taro"
import { isSetValue } from "@/utils/helper"

export const isTabbarPage = (pagePath: string): string | null => {
  const tabbars = [...Object.values(tabbarPages)]
  const index = tabbars.findIndex(tab => pagePath.includes(tab))
  if (index !== -1) {
    return tabbars[index]
  }
  return null
}

type StateToData<State extends Recordable, Data extends Recordable> = {
  [field in keyof State]: keyof Data
}

type ValidateScheme<State extends Recordable, Data extends Recordable, FieldMap extends StateToData<State, Data>> = {
  [Field in keyof State]: {
    field: Field
    dataField: FieldMap[Field]
    message: string
    getValue?(value: State[Field]): Data[FieldMap[Field]]
    validator?(value:State[Field]): boolean | void
  }
}

export function validateScheme<State extends Recordable, Data extends Recordable, FieldMap extends StateToData<State, Data>>(
  state: State,
  data: Data,
  stateToData: FieldMap,
  scheme: ValidateScheme<State, Data, FieldMap>
) {
  const schemeList = Object.values(scheme)
  for (let index = 0; index < schemeList.length; index++) {
    const { field, message, getValue, validator } = schemeList[index];
    if (!isSetValue(state[field]) || (typeof validator === 'function' && validator(state[field]) === false)) {
      Taro.showToast({
        title: message,
        icon: "error"
      })
      return false
    }
    data[stateToData[field]] = typeof getValue === 'function' ? getValue(state[field]) : state[field]
  }
  return true
}
export function getSalaryText(job: {salaryMin?: number; salaryMax?: number}) {
  const parts: string[] = []
  if (!job.salaryMin && !job.salaryMax) return "面议"
  ;[job.salaryMin, job.salaryMax].forEach(salary => {
    if (salary) {
      if (salary < 10_000) {
        parts.push(salary + "")
      } else if (salary < 100_000) {
        parts.push(Math.trunc(salary/1000) + "K")
      } else {
        parts.push(Math.trunc(salary/10000) + "万")
      }
    } else {
      parts.push("")
    }
  })
  return parts.join("-")
}
export function handlePreview(url: string) {
  const ext = url.split(".").pop()
  if (ext && ["pdf", "PDF"].includes(ext)) {
    Taro.downloadFile({
      url,
      success: function (res) {
        Taro.openDocument({
          filePath: res.tempFilePath,
          fail(res) {
            showErrorTip(res.errMsg)
          },
        })
      },
      fail(res) {
        showErrorTip(res.errMsg)
      },
    })
  } else {
    Taro.previewImage({
      current: url,
      urls: [url],
      fail(res) {
        showErrorTip(res.errMsg)
      },
    })
  }
  function showErrorTip(content: string) {
    Taro.showModal({
      title: "预览失败",
      content
    })
  }
}
